<?php
namespace Common\Logic;

use Common\Logic\ImLogic;

/**
 * 电话号码处理
 */
class TelBookLogic
{
	const LOCAL_TEL_BOOK_CACHE_KEY = "LOCAL_TEL_BOOK_CACHE_";

	/**
	* 电话号码格式处理
	*
	*/ 
	public static function dealTel($tel)
	{
	   	return str_replace(array("+86","-"," ",")","(",".","*","#"), "", $tel);
	}

	/**
	* 保存用户电话号码簿
	* @param mobile 数组
	* @param user_id
	*/ 
	public static function saveTelBook($mobile,$user_id)
	{
		if(empty($user_id))
			return ['status'=>0,'msg'=>'empty user_id','result'=> '' ];

		$mobile = !is_array($mobile) ? json_decode($mobile,TRUE) : $mobile;

		if(empty($mobile)||!is_array($mobile))
			return ['status'=>0,'msg'=>'empty telbook','result'=> '' ];

		$mobile = array_unique($mobile);

		if(empty($mobile)||!is_array($mobile))
			return ['status'=>0,'msg'=>'empty telbook','result'=> '' ];


		$local = S(self::LOCAL_TEL_BOOK_CACHE_KEY.$user_id);

		if( empty($local) )
		{
			$local = [
				"all" => [],
				"reg" => [],
				"friend" => []
			];
		}

		foreach ($mobile as &$value) 
		{
			$value = self::dealTel($value);
		}

		$local['all'] = $mobile;

	   	#保存到本地
	   	S(self::LOCAL_TEL_BOOK_CACHE_KEY.$user_id,$local);

	   	return ['status'=>1,'msg'=>'ok','result'=> ''];

	}

	/**
	* 分析用户电话号码簿
	* @param user_id
	*/
	public static function analyseTelBook($user_id)
	{
		if(empty($user_id))
			return ['status'=>0,'msg'=>'empty user_id','result'=> '' ];

		$local = S(self::LOCAL_TEL_BOOK_CACHE_KEY.$user_id);

		if(empty($local) || empty($local['all']))
			return ['status'=>0,'msg'=>'empty mobile','result'=> '' ];

		$diff = array_diff($local['all'],$local['reg']);

		#分析注册情况
		$user = [];
		foreach ($diff as $value) 
		{
			if( !in_array($value, $local['reg']) )
			{
				$user[$value] = self::isReg( $value );
				if( $user[$value] )
				{
					array_push($local['reg'],$value);
				}
			}
		}
		unset($value);

		#分析是否好友
		$ImLogic = new ImLogic;
		$local['friend'] = [];
		$local['unfriend'] = [];
		foreach ($local['reg'] as $value) 
		{
			if( !isset($user[$value]) || empty( $user[$value] ) )
			{
				$user[$value] = self::getUserInfoByTel( $value );
			}

			if( $user_id != $user[$value]['user_id'] )
			{
				if( $ImLogic->isFriend($user_id,$user[$value]['user_id'],TRUE) )
				{
					$local['friend'][] =  $user[$value]['user_id'];
				}else{
					$local['unfriend'][] =  $user[$value]['user_id'];
				}
			}
		}
		unset($value);

		#保存文件
		S(self::LOCAL_TEL_BOOK_CACHE_KEY.$user_id,$local);

		return ['status'=>1,'msg'=>'ok','result'=> $local ];
	}

	/**
	* 获取电话本中的推荐用户
	*
	*/ 
	public static function getRecomand($user_id )
	{
		if( empty($user_id) )
			return ['status'=>0,'msg'=>'empty user_id','result'=> '' ];

		$local = S(self::LOCAL_TEL_BOOK_CACHE_KEY.$user_id);

		if(empty($local) || empty($local['all']))
			return ['status'=>1,'msg'=>'ok','result'=> [] ];

		if( !isset($local['unfriend']) )
		{
			$result = self::analyseTelBook($user_id);
			$local = $result['result'];
		}

		$result = [];

		$recomands = array_slice($local['unfriend'], 0,10);

		$ImLogic = new ImLogic;

		foreach ($recomands as $value) 
		{
			if(!$ImLogic->isFriend($user_id,$value,TRUE))
			{
				$user = self::getUserInfoById($value);
				if( $user ) $result[] = $user;
			}
		}
		unset($value);
		return ['status'=>1,'msg'=>'ok','result'=> $result ];
	}


	/**
	   * 电话本检测
	   * @param $tels array 一次最多20个
	   * @param $user_id 
	*/ 
    public static function chkTelBook($tels = [],$user_id)
    {
      $me = self::getUserInfoById($user_id);

      $mark = 0;
      $res = [];
      $tels = !is_array($tels) ? [$tels] : $tels;
      $ImLogic = new ImLogic;
      foreach ($tels as $key) {
         if($mark<20){
            $key = (string)$key;
            $newkey = self::dealTel($key);
            $uinfo = [];
            if(is_numeric($key)){
               $user = self::getUserInfoByTel($newkey);
               if(!$user){
                  $uinfo['is_reg'] = FALSE;
                  $uinfo['is_self'] = FALSE;
                  $uinfo['is_follow'] = FALSE;
               }else{
                  $uinfo['is_reg'] = TRUE;
                  $uinfo['is_self'] = $me['user_id'] == $user['user_id'];
                  $uinfo['is_follow'] = $ImLogic->isFriend( $user_id,$user['user_id'],TRUE );
               }
            }
            $uinfo['mobile'] = $key;
            $where['mobile'] = $uinfo['mobile'];
            $id = M('users')->field('user_id')->where($where)->find();
            $uinfo['user_id'] = $id['user_id'];
            array_push($res, $uinfo);              
         }
         $mark++;
      }
      unset($key);

      return $res;
    }

	/**
	* 检查号码是否注册
	*
	*/ 
	public static function isReg($tel,$check = FALSE )
	{
		$user = self::getUserInfoByTel($tel);
		return  $user ? ( $check ? TRUE : $user ) : FALSE;
	}

	public static function getUserInfoById( $id )
    {
		$res = M("users")->where(["user_id"=>$id])->field("user_id,sex,nickname,head_pic,mobile")->find();
		
		if( $res )
		{
			$res['head_pic'] = parseMediaUrl($res['head_pic']);
		}

		return $res;
	}

	public static function getUserInfoByTel( $tel )
    {
      	$res = M("users")->where(["mobile"=>$tel])->field("user_id,sex,nickname,head_pic,mobile")->find();
		
		if( $res )
		{
			$res['head_pic'] = parseMediaUrl($res['head_pic']);
		}

		return $res;
	}

     
}
